//
//  Fraction.m
//  RunCloundA
//
//  Created by ChenXiaWen on 16/4/5.
//  Copyright © 2016年 ChenXiaWen. All rights reserved.
//

#import "Fraction.h"

#import "ViewController.h"


@implementation Fraction

@synthesize centralManager;
@synthesize mutableData;
@synthesize find_peripheral;

-(id) init
{
    self = [super init];
    
    centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    peripheral_array = [NSMutableArray array];
    
    return self;
}

-(void) print
{
    NSLog(@"this is a call from Fraction");
    [centralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES}];
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
            //判断状态开始扫瞄周围设备 第一个参数为空则会扫瞄所有的可连接设备  你可以
            //指定一个CBUUID对象 从而只扫瞄注册用指定服务的设备
            //scanForPeripheralsWithServices方法调用完后会调用代理CBCentralManagerDelegate的
            //- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI方法
        case CBCentralManagerStatePoweredOn:
            [[[ViewController instance] lableMsg] setText:@"当前可使用中心服务"];

            NSLog(@"centermanagerpower on");
            break;
        default:
        {
            NSString *msg = [NSString stringWithFormat:@"当前服务状态未知，%ld",(long)central.state];
            [[[ViewController instance] lableMsg] setText:msg];
        }
        break;
    }
    NSLog(@"centralManagerDidUpdateState %d",central.state);
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    if (peripheral) {
        self.find_peripheral = peripheral;
        //发现设备后即可连接该设备 调用完该方法后会调用代理CBCentralManagerDelegate的- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral表示连接上了设别
        //如果不能连接会调用 - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
        //
        // hide [centralManager connectPeripheral:peripheral options:@{CBConnectPeripheralOptionNotifyOnConnectionKey : @YES}];
        NSString *UUID = [peripheral.identifier UUIDString];
        NSString *UUID1 = [peripheral name];
        NSLog(@"----发现外设----uuid:%@  name:%@", UUID,UUID1);
        
        [peripheral_array addObject:peripheral];
        [[ViewController instance] AddListItem:UUID1];
        [self.centralManager stopScan];
        
        if (self.find_peripheral != peripheral)
        {
            self.find_peripheral = peripheral;
            NSLog(@"Connecting to peripheral %@", peripheral);
            
            //[self.centralManager connectPeripheral:peripheral options:nil];
        }
    }
}

-(void) connectDevice
{
    [self.centralManager connectPeripheral:self.find_peripheral options:nil];
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    NSLog(@"has connected");
    [mutableData setLength:0];
    self.find_peripheral.delegate = self;
    //此时设备已经连接上了  你要做的就是找到该设备上的指定服务 调用完该方法后会调用代理CBPeripheralDelegate（现在开始调用另一个代理的方法了）的
    //- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
    [self.find_peripheral discoverServices: nil];
    
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    //此时连接发生错误
    NSLog(@"connected periphheral failed");
    UIAlertView *myAlertView;
    myAlertView = [[UIAlertView alloc]initWithTitle:@"错误" message:@"连接蓝牙设备错误" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [myAlertView show];
}

#pragma mark -- CBPeripheralDelegate
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    if (error==nil) {
        
        //在这个方法中我们要查找到我们需要的服务  然后调用discoverCharacteristics方法查找我们需要的特性
        //该discoverCharacteristics方法调用完后会调用代理CBPeripheralDelegate的
        //- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
        for (CBService *service in peripheral.services) {
            //if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
              //  [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:kCharacteristicUUID]] forService:service];
            //}
            NSLog(@"dicover service %@",service.UUID);
        }
    }
}


@end
